//
//  RequestService+Home.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/27.
//

import UIKit
import Alamofire
import Swime
extension RequestService {
    func create_story(message: String, completeClosure: ((AIStreamMessage?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId": system_id,
                                                               "timestamp": time])
        let request = session.streamRequest("\(apiHost)/api/novel/create_story_v2",
                                            method: .post,
                                            parameters: ["message": message,
                                                         "sign": sign,
                                                         "timestamp": time])
        var dataStr = ""
        request.validate() // 可选的数据验证
        request.responseStream { stream in
            switch stream.event {
            case let .stream(result):
                switch result {
                case let .success(data):
                    if let responseString = String(data: data, encoding: .utf8) {
                        let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                        if let jsonDic = JSON as? [String: Any],
                           let current = jsonDic["code"] as? String, current != "200" {
                            GlobalRx.requestErrSubject.onNext(ReqServerCode(code: Int(current) ?? 0, msg: jsonDic["msg"] as? String))
                            completeClosure?(nil) // 处理不了的情况下，传空
                        }else {
                            
                            dataStr = dataStr + responseString
                        }
                    } else {
                        completeClosure?(nil) // 处理不了的情况下，传空
                    }
                case let .failure(error):
                    failureClosure?(error.localizedDescription)
                    XLog.d("chat_v1", "stream error", error)
                }
            case .complete:
                if dataStr.count > 0 {
                    let model = AIStreamMessage.parseMessageFromResponse(response: dataStr)
                    completeClosure?(model)
                }
                // 处理流结束的情况
                // 这里可以执行一些清理工作或者提示操作完成
                break
            }
        }
    }
    
    
    func videoStyle_list(completeClosure: ((PaintingModel) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/novel/style_list",
                        method: .post,
                        parameters: ["timestamp":time, "sign":sign], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let data = result["data"] as? [String: Any], let model = PaintingModel.deserialize(from: data) else { return }
                completeClosure?(model)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func videoVoice_list(completeClosure: (([VideoVoiceModel]) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/novel/voice_list",
                        method: .post,
                        parameters: ["timestamp":time, "sign":sign], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [[String:Any]], var model = [VideoVoiceModel].deserialize(from: result) else { return }
                if !model.isEmpty {
                    model[0]?.isSelect = true
                }
                completeClosure?(model.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func create_Video(title:String, message:String, style_id:String, proportion_id:String, voice_id:String, completeClosure: ((String) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "style_id":style_id,
                                                               "proportion_id":proportion_id,
                                                               "voice_id":voice_id])
        session.request("\(apiHost)/api/novel/create_video",
                        method: .post,
                        parameters: ["timestamp":time,
                                     "sign":sign,
                                     "title":title,
                                     "message":message,
                                     "style_id":style_id,
                                     "proportion_id":proportion_id,
                                     "voice_id":voice_id,
                                     "show_caption":"1",
                                     "speed":"1"
                                     ], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let checkId = result["checkId"] as? String else { return }
                completeClosure?(checkId)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func videoHistory(completeClosure: (([VideoHistoryModel]) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "page":"1"])
        session.request("\(apiHost)/api/novel/result_list",
                        method: .post,
                        parameters: ["timestamp":time, "sign":sign, "page":"1"], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let contentArr = result["content"] as? [[String: Any]], var models = [VideoHistoryModel].deserialize(from: contentArr) else { return }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func getCheckVdieo(checkId:String, completeClosure: ((VideoHistoryModel?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "outTradeNo":checkId])
        session.request("\(apiHost)/api/novel/check_info",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign,
                                     "outTradeNo":checkId
                                    ])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String : Any], let model = VideoHistoryModel.deserialize(from: result) else { 
                    failureClosure?("")
                    return
                }
                completeClosure?(model)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func videoDescs(completeClosure: (([String: Any]) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/novel/descs",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign
                                    ])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String : Any], let content = result["content"] as? [String : Any] else {
                    return
                }
                completeClosure?(content)
            case let .failure(error):
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
}

